<?php

namespace App\Http\Controllers\Server;

use App;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Cookie;
use Illuminate\Support\Facades\Response;
use Agoni\Lib\File;
use Agoni\Lib\Image;

class IndexController extends Controller
{
    protected $global=array();
    public  function __construct()
    {
        $this->global=[
           'version'=> Config::get('kefu.version'),
            'socket' => Config::get('kefu.socket')
        ];
    }
    public  function login(Request $request){
        if($request->isMethod('post')){
            $userName = input('username');
            $password = input('password');
            $user = db('users')->where('user_name', $userName)->row();

            if(empty($user)){
                return json(['code' => -1, 'data' => '', 'msg' => '客服不存在']);
            }

            if(md5($password . Config::get('kefu.salt')) != $user['user_pwd']){
                return json(['code' => -2, 'data' => '', 'msg' => '密码错误']);
            }

            // 设置session标识状态
            cookie1('l_user_name', $user['user_name'], Config::get('kefu.save_time'));
            cookie1('l_user_id', $user['id'], Config::get('kefu.save_time'));
            cookie1('l_user_avatar', $user['user_avatar'], Config::get('kefu.save_time'));

            return json(['code' => 1, 'data' => "/server/index", 'msg' => '登录成功']);
        }else{
            $data=$this->global;
            return view('kefu.login', $data);
        }
    }
    public function logout(){
        cookie1('l_user_name', null);
        cookie1('l_user_id', null);
        cookie1('l_user_avatar', null);
        $this->redirect(url('login/index'));
    }
    public function index(Request $request)
    {
        // 客服信息
        $userInfo = db('users')->where('id','=', cookie1('l_user_id'))->row();

        $info=[
            'uinfo' => $userInfo,
            'word' => db('words')->select(),
            'groups' => db('groups')->where('status', 1)->get(),
            'status' => db('kf_config')->where('id', 1)->row()
        ];
        $data=array_merge($info,$this->global);
        return view('kefu.index',$data);
    }

    // 获取服务用户列表
    // 此方法是为了防止客服工作期间错误的刷新工作台，导致服务人员消失的问题
    public function getUserList(Request $request)
    {
        if($request->isMethod('ajax')){
            // 此处只查询过去 三个小时 内的未服务完的用户
            $userList = db('service_log')->select('distinct user_id id,user_name name,user_avatar avatar,user_ip ip')
                ->where('kf_id', cookie1('l_user_id'))
                ->where('start_time', '>', time() - 3600 * 3)->where('end_time', 0)->get();

            return json(['code' => 1, 'data' => $userList, 'msg' => 'ok']);
        }
    }

    // 获取聊天记录
    public function getChatLog(Request $request)
    {
        if($request->isMethod('ajax')){

            $param = $request->input();

            $limit = 10; // 一次显示10 条聊天记录
            $offset = ($param['page'] - 1) * $limit;

            $logs = db('chat_log')->whereBrackets(function($query) use($param){
                $query->where('from_id', $param['uid'])->where('to_id', 'KF' . cookie1('l_user_id'));
            })->orWhereBrackets(function($query) use($param){
                $query->where('from_id', 'KF' . cookie1('l_user_id'))->where('to_id', $param['uid']);
            })->limit($offset, $limit)->orderby('id', 'desc')->get();

            $total =  db('chat_log')->whereBrackets(function($query) use($param){
                $query->where('from_id', $param['uid'])->where('to_id', 'KF' . cookie1('l_user_id'));
            })->orWhereBrackets(function($query) use($param){
                $query->where('from_id', 'KF' . cookie1('l_user_id'))->where('to_id', $param['uid']);
            })->count("*");
            foreach($logs as $key=>$vo){
                $logs[$key]['type'] = 'user';
                $logs[$key]['time_line'] = date('Y-m-d H:i:s', $vo['time_line']);
                if($vo['from_id'] == 'KF' . cookie1('l_user_id')){
                    $logs[$key]['type'] = 'mine';
                }
            }

            return json(['code' => 1, 'data' => $logs, 'msg' => intval($param['page']), 'total' => ceil($total / $limit)]);
        }
    }

    // ip 定位
    public function getCity(Request $request)
    {
        $ip =$request->input('ip');

        $ip2region = new \Ip2Region();
        $info = $ip2region->btreeSearch($ip);

        $city = explode('|', $info['region']);

        if(0 != $info['city_id']){
            return json(['code' => 1, 'data' => $city['2'] . $city['3'] . $city['4'], 'msg' => 'ok']);
        }else{
            return json(['code' => 1, 'data' => $city['0'], 'msg' => 'ok']);
        }
    }
    //上传图片
    public function UploadImg()
    {
        $Image=new Image();
        $info=$Image->save();
        if($info['code']==0){
            return json(['code' => 0, 'data' => ['src' => $info['uri'] ], 'msg' => '']);
        }else{
            // 上传失败获取错误信息
            return json(['code' => -1, 'data' => '', 'msg' => '上传失败']);
        }
    }

    //上传文件
    public function UploadFile()
    {
        $Image=new File();
        $info=$Image->save();
        if($info['code']==0){
            return json(['code' => 0, 'data' => ['src' => $info['uri'] ], 'msg' => '']);
        }else{
            // 上传失败获取错误信息
            return json(['code' => -1, 'data' => '', 'msg' => '上传失败']);
        }
    }
}

?>

